#include "myinet.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "tools.h"

static int
here_is_your_date_time(int sockfd){
    time_t now;
    time(&now);
    const char* time_string = ctime(&now);

    return write(sockfd, time_string, strlen(time_string));
}

int
main(int argc, char** argv){
    if (argc < 2){
        fprintf(stderr, "Usage: %s <port number>\n", argv[0]);
        exit(-1);
    }

    int portNumber = atoi(argv[1]);
    int sockfd;
    struct sockaddr_in incomming_addr;
    socklen_t addrlen = sizeof(incomming_addr);

    sockfd = get_server_socket(portNumber, SOCK_STREAM, 32);
    if (sockfd < 0){
        error_exit("get_server_socket", "failed to get socket");
    }
    info("listening to port %d", portNumber);

    // 循环等待连接

    int newsockfd = -1;
    while ((newsockfd =
                accept(sockfd, (struct sockaddr*)&incomming_addr, &addrlen)) > 0) {
        const char* req_host = inet_ntoa(incomming_addr.sin_addr);
        int req_port = ntohs(incomming_addr.sin_port);

        info("connection from %s:%d", req_host, req_port);
        int size = here_is_your_date_time(newsockfd);
        if (size < 0){
            warn("failed to write to %s:%d\n", req_host, req_port);
        }

        close(newsockfd);
    }

    error_exit("", 0);

    return 0;
}
